﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Toolkit.Web.Infastructure;
using Toolkit.Web.ExtensionMethods;
using System.Web;
using Toolkit.Web.Resources;

namespace Toolkit.Web.ViewComponents.DataGrid
{
    public sealed class DataGridMenuHelper<T> where T : class
    {
        public DataGridMenuHelper(IReadOnlyDataGrid<T> dataGrid)
        {
            if (dataGrid == null)
            {
                throw new ArgumentNullException("dataGrid");
            }

            ReadOnlyDataGrid = dataGrid;
        }

        public IReadOnlyDataGrid<T> ReadOnlyDataGrid
        {
            get;
            private set;
        }

        public IHtmlString ColumnSortDirectionSection()
        {
            StringBuilder markup = new StringBuilder();

            string format = @"<div class=""vc-dg-menuItem"" data-sort-desc=""{1}"" title=""{0}""><span class=""vc-icon""></span><span class=""vc-text"">{0}</span></div>";
            markup.Append(@"<div class=""vc-dg-sortMenu"">");

            markup.AppendFormat(
                format,
                HttpUtility.HtmlEncode(Language.ViewComponents_DataGrid_SortAscending),
                bool.FalseString
            );
            markup.AppendFormat(
                format,
                HttpUtility.HtmlEncode(Language.ViewComponents_DataGrid_SortDescending),
                bool.TrueString
            );

            markup.Append(@"</div>");

            return HtmlStringExtensions.Create(markup.ToString());
        }

        public IHtmlString ColumnVisibilitySection()
        {
            StringBuilder markup = new StringBuilder();

            string format = @"<div class=""vc-dg-menuItem"" data-col-key=""{1}"" data-visible=""{2}""><span class=""vc-icon""></span><span class=""vc-text"">{0}</span></div>";
            markup.Append(@"<div class=""vc-dg-visibilityMenu"">");

            foreach (DataGridColumn<T> column in ReadOnlyDataGrid.Columns.Where(c => c.Settings.EnableHidingAndShowing && !HtmlStringExtensions.IsNullOrEmpty(c.Label)))
            {
                markup.AppendFormat(
                    format,
                    column.Label,
                    column.Settings.Key,
                    column.Settings.IsVisible.ToString()
                );
            }

            markup.Append(@"</div>");

            return HtmlStringExtensions.Create(markup.ToString());
        }
    }
}
